const makeOrder = require('./wxpay_order/index');
const queryOrderByOutTradeNo = require('./wxpay_query_order_by_out_trade_no/index');
const queryOrderByTransactionId = require('./wxpay_query_order_by_transaction_id/index');
const refund = require('./wxpay_refund/index');
const refundQuery = require('./wxpay_refund_query/index');

// 云函数入口函数
exports.main = async (event, context) => {
    console.log('wxpayFunctions 收到请求:', { type: event.type, event });
    
    switch (event.type) {
        case 'wxpay_order':
            return await makeOrder.main(event, context);
        case 'wxpay_query_order_by_out_trade_no':
            return await queryOrderByOutTradeNo.main(event, context);
        case 'wxpay_query_order_by_transaction_id':
            return await queryOrderByTransactionId.main(event, context);
        case 'wxpay_refund':
            return await refund.main(event, context);
        case 'wxpay_refund_query':
            return await refundQuery.main(event, context);
        case 'wxpay_callback':
            // 支付回调处理
            return await handlePaymentCallback(event, context);
        default:
            return {
                code: -1,
                msg: 'Unimplemented method: ' + event.type
            };
    }
};

/**
 * 处理微信支付回调
 * @param {Object} event 事件对象
 * @param {Object} context 上下文对象
 */
async function handlePaymentCallback(event, context) {
    try {
        console.log('处理微信支付回调:', event);
        
        // 调用主云函数的支付回调处理
        const cloud = require('wx-server-sdk');
        const res = await cloud.callFunction({
            name: 'cloud',
            data: {
                action: 'payment/callback',
                ...event.callbackData
            }
        });
        
        return res.result;
    } catch (error) {
        console.error('支付回调处理失败:', error);
        return {
            code: -1,
            msg: '支付回调处理失败: ' + error.message
        };
    }
}

